<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createUserName">
        <el-input
          v-model="queryParams.createUserName"
          placeholder="请输入创建人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="open = true"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['file:recode:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="fileId" />
      <!-- <el-table-column label="文件url" align="center" prop="url" /> -->
      <el-table-column label="文件名称" align="center" prop="name" />
      <el-table-column label="创建人" align="center" prop="createUserName" />
      <!-- <el-table-column label="创建人id" align="center" prop="createUserId" /> -->
      <el-table-column label="加密类型" align="center" prop="encryptType" >
        <template slot-scope="scope">
          {{dict.type.encrypt_type[scope.row.encryptType].label}}
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建人id" align="center" prop="createUserId" /> -->
      <el-table-column label="是否加密" align="center" prop="isEncrypt" >
        <template slot-scope="scope">
          <!-- <div v-for="dict in dict.type.encrypt_status" v-if="dict.value  == scope.row.isEncrypt">{{dict.label}}</div> -->
           {{dict.type.encrypt_status[scope.row.isEncrypt].label}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownLoad(scope.row)"
            v-if="scope.row.isEncrypt == 1"
            v-hasPermi="['file:recode:edit']"
          >解密下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCommonDownLoad(scope.row)"
            v-hasPermi="['file:recode:edit']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleUpdate(scope.row, 1)"
            v-if="scope.row.isEncrypt == 0 && scope.row.encryptType != 0"
          >加密</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleUpdate(scope.row, 0)"
            v-if="scope.row.isEncrypt == 1"
          >解密</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['file:recode:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="文件url" prop="url">
          <el-input v-model="form.url" placeholder="请输入文件url" />
        </el-form-item> -->
        <el-form-item label="上传文件" prop="url">
          <el-upload
            multiple
            :action="uploadFileUrl"
            :before-upload="handleBeforeUpload"
            :file-list="fileList"
            :limit="limit"
            :on-error="handleUploadError"
            :on-exceed="handleExceed"
            :on-success="handleUploadSuccess"
            :headers="headers"
            class="upload-file-uploader"
            ref="fileUpload"
          >
            <!-- 上传按钮 -->
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <!-- <el-upload
            class="upload-demo"
            action=".#"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="fileList">
          </el-upload> -->
        </el-form-item>
          <el-form-item label="加密类型" prop="encryptType">
             <el-radio-group v-model="form.encryptType" size="small">
                <el-radio
                  border
                  v-for="dict in dict.type.encrypt_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
            </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRecode, getRecode, delRecode, addRecode, updateRecode } from "@/api/file/recode";
import { listType, getType, delType, addType, updateType, refreshCache } from "@/api/system/dict/type";
import { getToken } from "@/utils/auth";
import { log } from 'util';

export default {
  name: "Recode",
  dicts: ['encrypt_type','encrypt_status'],
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      file: {},
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      recodeList: [],
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      // 弹出层标题
      title: "",
      number: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        url: null,
        name: null,
        createUserName: null,
        createUserId: null,
        encryptType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
          encryptType: [
          { required: true, message: "问卷类型不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listRecode(this.queryParams).then(response => {
        this.recodeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        url: null,
        name: null,
        createTime: null,
        createUserName: null,
        createUserId: null,
        encryptType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row, status) {
      this.reset();
      row.isEncrypt = status
      updateRecode(row).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList()
      });
    },
    /** 新增按钮 */
    submitForm() {
     if(this.fileList && this.fileList.length <= 0) {
       this.$modal.msgError("请上传文件");
         return
     }
      let that = this
      this.$refs["form"].validate(valid => {
        if (valid) {
          let submit = []
          for (let i = 0; i < this.fileList.length; i++) {
            submit.push({
              url: this.fileList[i].url,
              name: this.fileList[i].name,
              encryptType: this.form.encryptType,
            })
          }
          addRecode(JSON.parse(JSON.stringify(submit))).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.fileList= [];
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + fileIds + '"的数据项？').then(function() {
        return delRecode(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('file/recode/export', {
        ...this.queryParams
      }, `recode_${new Date().getTime()}.xlsx`)
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      // if (this.fileType) {
      //   const fileName = file.name.split('.');
      //   const fileExt = fileName[fileName.length - 1];
      //   const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
      //   if (!isTypeOk) {
      //     this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
      //     return false;
      //   }
      // }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      // this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: file.name, url: res.fileName });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        // this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        // this.$modal.closeLoading();
      }
    },
     // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    handleDownLoad(file) {
      let suffix = file.url.substring(file.url.lastIndexOf("."), file.url.length);
       this.download('file/recode/en/download', {
        ...file
      }, `${file.name}_${new Date().getTime() + suffix}`)
    },
    handleCommonDownLoad(file) {
      let suffix = file.url.substring(file.url.lastIndexOf("."), file.url.length);
       this.download('file/recode/de/download', {
        ...file
      }, `${file.name}_${new Date().getTime() + suffix}`)
    }
  }
};
</script>
